<template>
  <div class="users-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><User /></el-icon>
          <span>用户管理</span>
        </div>
      </template>
      
      <div class="page-content">
        <!-- 搜索区域 -->
        <div class="search-section">
          <div class="search-form">
            <div class="search-input-wrapper">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入用户名进行搜索"
                size="large"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="search-buttons-wrapper">
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                @click="handleSearch"
              >
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button
                size="large"
                @click="handleReset"
              >
                重置
              </el-button>
            </div>
          </div>
        </div>

        <!-- 批量操作区域 -->
        <div class="batch-actions">
          <el-button
            type="danger"
            size="default"
            :disabled="selectedUsers.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedUsers.length }})
          </el-button>
        </div>

        <!-- 用户列表表格 -->
        <div class="table-section">
          <el-table
            :data="userList"
            :loading="loading"
            stripe
            border
            style="width: 100%"
            empty-text="暂无用户数据"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="userId" label="用户ID" min-width="80" align="center" />
            <el-table-column prop="username" label="用户名" min-width="120" align="center" />
            <el-table-column prop="phone" label="手机号" min-width="140" align="center" />
            <el-table-column prop="roleId" label="角色ID" min-width="80" align="center" />
            <el-table-column prop="isSuper" label="角色名称" min-width="120" align="center">
              <template #default="scope">
                <el-tag
                  :type="scope.row.isSuper === true ? 'danger' : 'primary'"
                  size="small"
                >
                  {{ scope.row.isSuper === true ? '超级管理员' : '普通管理员' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" min-width="160" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)">
                  修改
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            :loading="loading"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 修改用户弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改用户信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="用户ID">
          <el-input v-model="editForm.userId" disabled />
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="editForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="editForm.phone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="角色ID">
          <el-input v-model="editForm.roleId" disabled />
        </el-form-item>
        
        <el-form-item label="角色名称">
          <el-tag
            :type="editForm.isSuper === true ? 'danger' : 'primary'"
            size="default"
          >
            {{ editForm.isSuper === true ? '超级管理员' : '普通管理员' }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="创建时间">
          <el-input :value="formatDateTime(editForm.createTime)" disabled />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="editLoading"
            @click="handleSubmitEdit"
          >
            提交修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Search, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const userList = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedUsers = ref<number[]>([])
const editDialogVisible = ref(false)
const editFormRef = ref()
const editLoading = ref(false)

// 定义用户编辑表单类型
interface EditUserForm {
  userId: number | string
  username: string
  phone: string
  roleId: number | string
  isSuper: boolean
  createTime: string
}

const editForm = ref<EditUserForm>({
  userId: '',
  username: '',
  phone: '',
  roleId: '',
  isSuper: false,
  createTime: ''
})

// 保存原始数据用于比较
const originalEditForm = ref<EditUserForm>({
  userId: '',
  username: '',
  phone: '',
  roleId: '',
  isSuper: false,
  createTime: ''
})

// 表单验证规则
const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2到20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 用户列表查询函数
const fetchUserList = async (keyword: string = '', page: number = 1, limit: number = 10) => {
  loading.value = true
  
  try {
    // 获取登录token和用户名
    const token = localStorage.getItem('token')
    const username = localStorage.getItem('username')
    
    // 构建查询参数
    const params: any = {
      page: page,
      limit: limit
    }
    
    // 如果有关键词则添加到参数中
    if (keyword && keyword.trim()) {
      params.keyword = keyword.trim()
    }
    
    const response = await axios.get('/merchants/user', {
      params: params,
      headers: {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      }
    })
    
    const { code, message, data } = response.data

    if (code === 200) {
      // 假设后端返回的data结构为 { list: [], total: number }
      if (data) {
        userList.value = data.list || data.records || data || []
        total.value = data.total || data.totalCount || 0
      } else {
        userList.value = []
        total.value = 0
      }
    } else {
      ElMessage.error(message || '获取用户列表失败')
      userList.value = []
      total.value = 0
    }
    
  } catch (error: any) {
    console.error('获取用户列表失败:', error)
    
    if (error.response) {
      const status = error.response.status
      let errorMessage = '获取用户列表失败'
      
      if (status === 403) {
        errorMessage = '权限不足，请重新登录'
      } else if (status === 401) {
        errorMessage = '登录已过期，请重新登录'
      } else if (status === 404) {
        errorMessage = '接口不存在'
      }
      
      ElMessage.error(errorMessage)
    } else {
      ElMessage.error('网络连接失败，请检查网络')
    }
    
    userList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  fetchUserList(searchKeyword.value, currentPage.value, pageSize.value)
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  fetchUserList('', currentPage.value, pageSize.value)
}

// 分页大小改变
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchUserList(searchKeyword.value, currentPage.value, pageSize.value)
}

// 页码改变
const handlePageChange = (newPage: number) => {
  currentPage.value = newPage
  fetchUserList(searchKeyword.value, currentPage.value, pageSize.value)
}

// 编辑用户
const handleEdit = (user: any) => {
  // 复制用户数据到编辑表单
  editForm.value = {
    userId: user.userId,
    username: user.username,
    phone: user.phone,
    roleId: user.roleId,
    isSuper: user.isSuper,
    createTime: user.createTime
  }
  originalEditForm.value = {
    userId: user.userId,
    username: user.username,
    phone: user.phone,
    roleId: user.roleId,
    isSuper: user.isSuper,
    createTime: user.createTime
  }
  editDialogVisible.value = true
}

// 批量删除
const handleBatchDelete = () => {
  ElMessage.info(`批量删除用户：${selectedUsers.value.join(', ')}（功能开发中）`)
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection.map((item: any) => item.userId)
}

// 删除用户
const handleDelete = (user: any) => {
  ElMessage.info(`删除用户：${user.username}（功能开发中）`)
}

// 提交修改
const handleSubmitEdit = async () => {
  if (!editFormRef.value) return
  
  // 表单验证
  const valid = await editFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  editLoading.value = true
  
  try {
    // 获取登录token和用户名
    const token = localStorage.getItem('token')
    const username = localStorage.getItem('username')

    //判断用户是否真的做了修改，避免无用请求
    console.log(editForm.value.username);
    console.log(originalEditForm.value.username);
    if((editForm.value.username).trim() === originalEditForm.value.username.trim() && (editForm.value.phone).trim() === originalEditForm.value.phone.trim()){
      ElMessage.warning('您没有做任何修改，无需提交');
      return;
    }
    
    const response = await axios.put('/merchants/user/modify', {
      userId: editForm.value.userId,
      username: editForm.value.username,
      phone: editForm.value.phone,
    }, {
      headers: {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      }
    })
    
    const { code, message } = response.data

    if (code === 200) {
      ElMessage.success(message || '用户信息修改成功！')
      editDialogVisible.value = false
      
      // 刷新用户列表
      await fetchUserList(searchKeyword.value, currentPage.value, pageSize.value)
      
    } else {
      ElMessage.error(message || '修改失败，请重试')
    }
    
  } catch (error: any) {
    console.error('修改用户信息失败:', error)
    
    if (error.response) {
      const status = error.response.status
      let errorMessage = '修改失败'
      
      if (status === 403) {
        errorMessage = '权限不足，请重新登录'
      } else if (status === 401) {
        errorMessage = '登录已过期，请重新登录'
      } else if (status === 404) {
        errorMessage = '接口不存在'
      } else {
        errorMessage = error.response.data?.message || `服务器错误：${status}`
      }
      
      ElMessage.error(errorMessage)
    } else {
      ElMessage.error('网络连接失败，请检查网络')
    }
    
  } finally {
    editLoading.value = false
  }
}

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList()
})

// 格式化时间
const formatDateTime = (dateTimeString: string) => {
  if (!dateTimeString) return ''
  
  try {
    // 处理ISO格式的时间字符串，如 "2025-05-26T22:39:48"
    const date = new Date(dateTimeString)
    
    if (isNaN(date.getTime())) {
      return dateTimeString // 如果无法解析，返回原始字符串
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return dateTimeString // 错误时返回原始字符串
  }
}
</script>

<style scoped>
.users-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.header-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 20px;
}

.page-content {
  padding: 20px 0;
}

.search-section {
  margin-bottom: 16px;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  min-height: 40px;
}

.search-input-wrapper {
  flex: 0 0 300px;
}

.search-buttons-wrapper {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.batch-actions {
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.table-section {
  margin-bottom: 20px;
}

/* 表格单元格样式 */
.table-section :deep(.el-table) {
  border: 1px solid #dcdfe6;
}

.table-section :deep(.el-table th) {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
  text-align: center;
}

.table-section :deep(.el-table td) {
  text-align: center;
}

.table-section :deep(.el-table--border) {
  border: 1px solid #dcdfe6;
}

.table-section :deep(.el-table--border td) {
  border-right: 1px solid #dcdfe6;
}

.table-section :deep(.el-table--border th) {
  border-right: 1px solid #dcdfe6;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 分页组件样式优化 */
.pagination-section :deep(.el-pagination) {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.pagination-section :deep(.el-pagination__total) {
  margin-right: 10px;
}

.pagination-section :deep(.el-pagination__sizes) {
  margin-right: 10px;
}

.pagination-section :deep(.el-pagination__jump) {
  margin-left: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .users-container {
    padding: 0 16px;
  }
  
  .search-section {
    padding: 12px 16px;
  }
  
  .search-form {
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .search-input-wrapper {
    flex: 1 1 100%;
    min-width: 100%;
  }
  
  .search-input-wrapper .el-input {
    width: 100%;
  }
  
  .search-buttons-wrapper {
    flex: 1 1 100%;
    justify-content: center;
  }
  
  .search-buttons-wrapper .el-button {
    flex: 1;
    min-width: 80px;
  }
  
  .batch-actions {
    text-align: center;
    padding: 12px 0;
  }
  
  .pagination-section {
    overflow-x: auto;
    padding: 16px 0;
  }
  
  .pagination-section :deep(.el-pagination) {
    justify-content: center;
    flex-wrap: wrap;
  }
}

/* 弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 编辑表单样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
  cursor: not-allowed;
}

/* 移动端弹窗适配 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 5%;
  }
  
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  :deep(.el-form--label-top .el-form-item__label) {
    padding-bottom: 5px;
  }
}
</style> 